import { defineStore } from "pinia";
import { ref } from "vue";

interface ToDoItem {
  date: string;
  startTime: string;
  endTime: string;
  item: string;
  id: number;
  completed: boolean;
}

const id = ref(0);

export const useTodoListStore = defineStore(
  "todoList",
  () => {
    const todoList = ref<ToDoItem[]>([]);
    const addTodo = (
      item: string,
      date: string,
      startTime: string,
      endTime: string
    ) => {
      todoList.value.push({
        item,
        date,
        startTime,
        endTime,
        id: id.value++,
        completed: false,
      });
    };
    const toggleCompleted = (idToFind: number) => {
      const todo = todoList.value.find((obj) => obj.id === idToFind);
      if (todo) {
        todo.completed = !todo.completed;
      }
    };
    const deleteTodo = (itemID: number) => {
      todoList.value = todoList.value.filter((object) => {
        return object.id !== itemID;
      });
    };

    return {
      todoList,
      addTodo,
      toggleCompleted,
      deleteTodo,
    };
  },
  {
    unistorage: true, // 开启后对 state 的数据读写都将持久化
  }
);
